package com.wms.web.action;

import com.wms.model.Customer;
import com.wms.result.ResultMap;
import com.wms.result.ResultTab;
import com.wms.service.CustomerService;
import com.wms.utils.CommonUtils;
import com.wms.utils.SQLStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author This
 * @version 1.0
 * @date 2019/7/16 21:51
 */
public class CustomerAction extends BaseAction<Customer> {

    @Autowired
    private CustomerService service;

    @Override
    public void save() throws IOException {
        if (StringUtils.isEmpty(getModel().getCusName())) {
            responseJson(new ResultMap(0, "表单数据不正确！"), new String[]{"data"});
            return;
        }

        if (service.add(getModel())){
            responseJson(new ResultMap(1, "保存成功！"), new String[]{"data"});
            return;
        }
        responseJson(new ResultMap(0, "客户已经存在，请勿重复添加！"), new String[]{"data"});
    }

    @Override
    public void edit() {
        if (StringUtils.isEmpty(getModel().getCusName())) {
            try {
                responseStr("{\"status\":0,\"msg\":\"客户名称不能为空！\"}");
                return;
            } catch (IOException e) {
            }
        }
        service.edit(getModel());
        try {
            responseStr("{\"status\":1,\"msg\":\"保存成功！\"}");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete() throws IOException {
        if (getModel().getId() != null && getModel().getId() != 0) {
            service.delete(getModel());
        }
        if (StringUtils.isNotEmpty(ids)) {
            service.deleteAll(ids);
        }
        responseJson(new ResultMap(1, "删除成功！"));
    }

    public void deleteAll() {

    }

    @Override
    public void showList() {

    }

    public void getCus() throws IOException {
        if (getModel().getId() != null && getModel().getId() > 0) {
            Customer customer = service.find(getModel().getId());
            responseJson(customer, new String[]{""});
        }
    }

    public void pageList() throws Exception {
        if (!CommonUtils.hasPage(page, limit)) {
            responseJson(CommonUtils.failResult());
            return;
        }
        pb.setPageSize(limit);
        pb.setCurrentPage(page);
        Map<String, String> map = getModel().getAttr(getModel());
        if (map != null && map.size() > 0) {
            String condition = SQLStringUtils.toLikeString(map, "or");
            pb.setCondition(condition);
        }
        service.pageQuery(pb);
        ResultTab resultTab = CommonUtils.responseRst(pb);
        responseJson(resultTab);
    }
}
